package com.kamistoat.meimeichatserveraggrement.codec;

import com.kamistoat.meimeichatserveraggrement.protocol.Packet;
import com.kamistoat.meimeichatserveraggrement.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 编码器
 */
public class ObjEncoder extends MessageToByteEncoder<Packet> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Packet in, ByteBuf out) {
        try {
            byte[] data = SerializationUtil.serialize(in);
            out.writeInt(data.length + 1);
            out.writeByte(in.getCommand()); //添加指令
            out.writeBytes(data);
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }
}
